package js.lee.jvli.cron;

import it.sauronsoftware.cron4j.Scheduler;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import js.lee.jvli.config.TaskNode;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class JobManager {
    private static Logger  logger       = LoggerFactory.getLogger(JobManager.class);
    Map<String, Scheduler> schedulerMap = new HashMap<String, Scheduler>();
    Map<String, Runnable>  taskMap      = new HashMap<String, Runnable>();

    public JobManager(List<TaskNode> taskList)
            throws ClassNotFoundException, InstantiationException, IllegalAccessException {
        for (TaskNode task : taskList) {
            logger.info("Adding task:" + task.getName() + " " + task.getType());
            Class taskClass = Class.forName(task.getCallClassName());
            Runnable taskThread = (Runnable) taskClass.newInstance();
            if ("once".equals(task.getType())) {
                taskMap.put(task.getName(), taskThread);
            }
            else if ("cron".equals(task.getType())) {
                Scheduler s = new Scheduler();
                s.schedule(task.getTime(), taskThread);
                this.schedulerMap.put(task.getName(), s);
            }
            else {
                logger.error("Unsupported task type:");
            }
        }
    }

    public void start() {
        for (String taskName : this.schedulerMap.keySet()) {
            logger.info("Starting task:" + taskName);
            this.schedulerMap.get(taskName).start();
        }
        for (String taskName : this.taskMap.keySet()) {
            logger.info("Starting task:" + taskName);
            this.taskMap.get(taskName).run();
        }

    }

    public void stop() {
        for (String taskName : this.schedulerMap.keySet()) {
            logger.info("Stoping task:" + taskName);
            this.schedulerMap.get(taskName).stop();
        }
    }
}
